<template>
  <div class="tpl-content-wrapper">
    <ol class="am-breadcrumb">
      <li><a href="#" class="am-icon-home">首页</a></li>
      <li><a href="#">车位系统</a></li>
      <li>
        <router-link :to="{name: 'ProjectView'}">车位管理</router-link>
      </li>
      <li class="am-active">{{isNew ? '新增车位' : form.name}}</li>
    </ol>
    <div class="tpl-portlet-components">
      <button @click="save" type="button" class="am-btn am-btn-default am-btn-secondary">
        <span class="am-icon-save"></span> {{ id?'修改':'保存' }}
      </button>
      <button @click="changeState(form.srcMac)" type="button" class="am-btn am-btn-default am-btn-secondary">
        复位占用
      </button>
      <button @click="changeState1(form.srcMac)" type="button" class="am-btn am-btn-default am-btn-secondary">
        复位空闲
      </button>
    </div>
    <div class="am-panel-group" id="collapse-nav">
      <div class="am-panel am-panel-default">
        <div class="am-panel-hd">
          <span class="am-panel-title"><strong>基础数据</strong></span>

          <span class="color-999 am-text-xs am-kai" data-am-collapse="{target: '#do-not-say-1'}"> - 点击展开/折叠</span>
        </div>
        <div id="do-not-say-1" class="am-panel-collapse am-collapse am-in ">
          <div class="am-panel-bd tpl-amazeui-form">
            <!-- form -->
            <form id="form" action="" class="am-g am-form">
              <button id="submit" class="am-btn am-btn-secondary" type="submit" style="display:none;">提交</button>
              <div class="am-u-md-12">
                <div class="am-input-group">
                  <span class="am-input-group-label am-kai">车位名称</span>
                  <input type="text" class="am-form-field" placeholder="请输入车位名称" v-model="form.name" required>
                </div>
              </div>

              <div class="am-u-md-12">
                <div class="am-input-group">
                  <span class="am-input-group-label am-kai">车位地点</span>
                  <input type="text" class="am-form-field" placeholder="请输入车位地点" v-model="form.place" required>
                </div>
              </div>

              <div class="am-u-md-12">
                <div class="am-input-group">
                  <span class="am-input-group-label am-kai">车位编号</span>
                  <input type="text" class="am-form-field" placeholder="请输入车位编号" v-model="form.srcMac" required>
                </div>
              </div>

              <div class="am-u-md-12">
                <div class="am-input-group">
                  <span class="am-input-group-label am-kai">车位状态</span>
                  <select class="am-form-field" v-model="form.state">
                    <option value="1001">空闲中</option>
                    <option value="1002">占用中</option>
                  </select>
                </div>
              </div>

              <div class="am-u-md-12">
                <div class="am-input-group">
                  <span class="am-input-group-label am-kai">数据状态</span>
                  <select class="am-form-field" v-model="form.dState">
                    <option value="1">空闲</option>
                    <option value="2">被占用</option>
                    <option value="3">解锁中</option>
                    <option value="4">锁定中</option>
                    <option value="5">管理员锁定</option>
                  </select>
                </div>
              </div>

              <div class="am-u-md-12">
                <div class="am-input-group">
                  <span class="am-input-group-label am-kai">物理状态</span>
                  <input type="text" class="am-form-field" placeholder="请输入车位物理状态" v-model="form.state" required>
                </div>
              </div>

              <div class="am-u-md-12">
                <div class="am-input-group">
                  <span class="am-input-group-label am-kai">车位创建时间</span>
                  <input type="text" class="am-form-field" :value="form.ctime | date" disabled="disabled">
                </div>
              </div>
              <div class="am-u-md-12">
                <table class="am-input-group">
                  <tr>
                  <td class="am-input-group-label am-kai" rowspan="3">车位GPS</td>
                  <td class="am-input-group-label am-kai">
                    <span >原始坐标</span>
                  </td>
                  <td>
                    <span class="am-form-field gps">{{parkGPS.lat}},{{parkGPS.lon}}</span>
                  </td>
                  </tr>
                  <tr>
                    <td class="am-input-group-label am-kai">
                    <span >火星坐标</span>
                  </td>
                  <td>
                    <span class="am-form-field gps">{{parkGPS.ggLat}},{{parkGPS.ggLon}}</span>
                  </td>
                  </tr>
                  <tr>
                    <td class="am-input-group-label am-kai">
                    <span >百度坐标</span>
                  </td>
                  <td>
                    <span class="am-form-field gps">{{parkGPS.bdLat}},{{parkGPS.bdLon}}</span>
                  </td>
                  </tr>
                </table>
              </div>
              <div class="am-u-md-12">
                <table class="am-input-group">
                  <tr>
                  <td class="am-input-group-label am-kai" rowspan="3">基站GPS</td>
                  <td class="am-input-group-label am-kai">
                    <span >原始坐标</span>
                  </td>
                  <td>
                    <span class="am-form-field gps">{{stationGPS.lat}},{{stationGPS.lon}}</span>
                  </td>
                  </tr>
                  <tr>
                    <td class="am-input-group-label am-kai">
                    <span >火星坐标</span>
                  </td>
                  <td>
                    <span class="am-form-field gps">{{stationGPS.ggLat}},{{stationGPS.ggLon}}</span>
                  </td>
                  </tr>
                  <tr>
                    <td class="am-input-group-label am-kai">
                    <span >百度坐标</span>
                  </td>
                  <td>
                    <span class="am-form-field gps">{{stationGPS.bdLat}},{{stationGPS.bdLon}}</span>
                  </td>
                  </tr>
                </table>
              </div>
            </form>
            <!-- form end -->
          </div>
        </div>
      </div>
    </div>
    <div class="am-panel am-panel-default">
      <div class="am-panel-hd">
        <span class="am-panel-title">
          <strong>车位状态日志</strong>
        </span>
        <span class="color-999 am-text-xs am-kai" data-am-collapse="{target: '#do-not-say-7'}"> - 点击展开/折叠</span>
      </div>
      <div id="do-not-say-7" class="am-panel-collapse am-collapse">
        <div class="am-panel-bd">
          <bs-park-state-log :parkId="id"></bs-park-state-log>
        </div>
      </div>
    </div>
<!--     <div class="am-panel am-panel-default">
      <div class="am-panel-hd">
        <span class="am-panel-title"><strong>详细数据</strong></span>

        <span class="color-999 am-text-xs am-kai" data-am-collapse="{target: '#do-not-say-11'}"> - 点击展开/折叠</span>
      </div>
      <div id="do-not-say-11" class="am-panel-collapse am-collapse am-in ">
        <div class="am-panel-bd tpl-amazeui-form">
          
        </div>
      </div>
    </div> -->
    <alert :test="alertText"></alert>
    <confirm :show="confirm.show" :confirm="confirm" @onConfirm="onConfirm" @onCancel="onCancel"></confirm>
    <!-- <select-user @selectUserCheck="selectUserCheck"></select-user> -->
    <auth-msg></auth-msg>
  </div>
</template>

<script>
  import * as apis from '../../../apis'
  // import authCheck from 'assets/authCheck'
  export default {
    // mixins: [authCheck],
    data() {
      return {
        id: this.$route.params.id || '',
        form: {
          name: '', place: '', 
          state: '', srcMac: '',dState: '',
        },
        parkGPS: {},
        stationGPS: {},
        user: {},
        form2: { refundType: '1', refundDesc: '' },
        alertText: '',
        confirm: { show: false },
        valid: false, valid2: false, valid3: false, valid4: false,
        isNew: true
      }
    },
    created() {
      if (this.id) {
        this.isNew = false
        this.getProject()
      }
    },
    mounted() {
      let _this = this
      this.$nextTick(() => {
        $('#form').validator({
          // submit提交触发校验
          submit: function (e) {
            // 阻止提交按钮的默认 action
            e.preventDefault()
            let formValidity = this.isFormValid()
            _this.valid = formValidity
          }
        })
      })
    },
    methods: {
      save() {
        if (this.id) {
          console.log('id存在')
          this.updateProject(this.form)
          // this.getProject()
        } else {
          this.addProject()
          console.log('tianjiachewei')
        }
      },
      addProject() {
        // document.getElementById("submit").click()
        this.validate()
        this.validate2()
        // if (!this.valid) return
          apis.addProject(this.form).then(({data}) => {
          // if (this.authCheck(data)) return
          if (data.errcode == 0) {
            this.alertText = "保存成功"
            $('#my-alert').modal('toggle')
            // this.$router.push({ name: 'ProjectView', params: { id: data.result } })
            // this.id = data.result
            // this.isNew = false
            // this.getProject()
          } else { if (data.message) { this.alertText = "操作异常！"; $('#my-alert').modal('toggle') } }
        })
      },
      updateProject() {
        // this.validate()
        // if (!this.valid) return
        console.log('e',this.form)
        console.log('id2',this.id)
        apis.updateProject(this.id,this.form).then(({data}) => {
          if (data.errcode == 0) {
            this.alertText = "保存成功"
            $('#my-alert').modal('toggle')
          } else {
            if (data.message) { this.alertText = "操作异常！"; $('#my-alert').modal('toggle') }
          }
        })
      },
      getProject() {
        apis.getProject(this.id).then(({data}) => {
          console.log('data0',data)
          // if (this.authCheck(data)) return
          if (data.errcode == 0) {
            console.log('data',data)
            // this.preHandle(data.result)
            this.form.name = data.data.name
            this.form.place = data.data.place
            this.form.state = data.data.state
            this.form.srcMac = data.data.srcMac
            this.form.dState = data.data.dState
            this.form.ctime = data.data.ctime
            console.log('form',this.form)
            this.parkGPS = data.data.parkGPS
            this.stationGPS = data.data.stationGPS
            // this.generateQRcode(data.result.eid, this.id)
          }
        })
      },
      changeState(srcMac){
        console.log(srcMac)
        let state = '2002'
        console.log('state', state)
        apis.changeState(state, srcMac).then(({data: data}) => {
          console.log('state', 'chenggong')
          if (data.errcode === 0) {
            let that = this
            let timer = setInterval(function(){
              that.getProject()
              if(that.form.state == '1002'){
                that.alertText = "复位成功"
                $('#my-alert').modal('toggle')
                clearInterval(timer)
                that.form.state = '1002'
              }
            }, 1000)
            setTimeout(function(){
              if(that.form.state == '1001'){
                clearInterval(timer)
              that.alertText = "复位失败"
              $('#my-alert').modal('toggle')
              }else{}
            },12000)
          } else {
            this.lists = []
          }
        })
      },
      changeState1(srcMac){
        console.log(srcMac)
        let state = '2001'
        console.log('state', state)
        apis.changeState(state, srcMac).then(({data: data}) => {
          console.log('state', 'chenggong')
          if (data.errcode === 0) {
            let that = this
            let timer = setInterval(function(){
              that.getProject()
              if(that.form.state == '1001'){
                that.alertText = "复位成功"
                $('#my-alert').modal('toggle')
                clearInterval(timer)
                that.form.state = '1001'
              }
            }, 1000)
            setTimeout(function(){
              if(that.form.state == '1002'){
                clearInterval(timer)
              that.alertText = "复位失败"
              $('#my-alert').modal('toggle')
              }else{}
            },12000)
          } else {
            this.lists = []
          }
        })
      },
      preHandle(result) {
        if (!result.fundraisingType || result.fundraisingType == 'undefined') result.fundraisingType = '1'

          if (!result.hasSupplement || result.hasSupplement == '0') {
            result.hasSupplement = '0'
            result.supplement = { houseNum: '', houseValue: '', houseState: '0', carNum: '', carValue: '', carState: '0', seriousInsurance: '0', medicalInsurance: '0' }
          }
          if (!result.hasProve || result.hasProve == '0') {
            result.hasProve = '0'
            result.prove = { patient: '', type: '', payyee: '', typeHospital: '', patientHasId: '0', typeProve: '0', payeeHasId: '0', payeeHasRelation: '0' }
          }
        },
        passAudit() {
          apis.passAudit(this.form._id).then(({data}) => {
          // if (this.authCheck(data)) return
          if (data && data.result_code === 1) {
            this.form.state = '1'

            this.alertText = "操作成功！"
            $('#my-alert').modal('toggle')
          } else if (data.errcode === 90043) {
            this.alertText = "必须设置公众号信息后，项目才能开始筹款"
            $('#my-alert').modal('toggle')
          } else {

            this.alertText = "操作异常！"
            $('#my-alert').modal('toggle')
          }

        }, (res) => { this.alertText = "操作异常！"; $('#my-alert').modal('toggle') })
        },
        noPassAudit() {
          apis.noPassAudit(this.form._id).then(({data}) => {
          // if (this.authCheck(data)) return
          if (data && data.result_code === 1) {

            alert("数据删除成功！")
            this.$router.push({ name: "ProjectView" })
          } else {

            this.alertText = "操作异常！"
            $('#my-alert').modal('toggle')
          }

        }, (res) => { this.alertText = "操作异常！"; $('#my-alert').modal('toggle') })
        },
        stop() {
          apis.stop(this.form._id).then(({data}) => {
          // if (this.authCheck(data)) return
          if (data && data.result_code === 1) {
            this.form.state = '3'

            this.alertText = "操作成功！"
            $('#my-alert').modal('toggle')
          } else {

            this.alertText = "操作异常！"
            $('#my-alert').modal('toggle')
          }

        }, (res) => { this.alertText = "操作异常"; $('#my-alert').modal('toggle') })
        },
        restore() {
          apis.restore(this.form._id).then(({data}) => {
            if (data && data.result_code === 1) {
              this.form.state = '1'

              this.alertText = "操作成功！"
              $('#my-alert').modal('toggle')
            } else {

              this.alertText = "操作异常！"
              $('#my-alert').modal('toggle')
            }

          }, (res) => { this.alertText = "操作异常"; $('#my-alert').modal('toggle') })
        },
        end() {
          apis.end(this.form._id).then(({data}) => {
          // if (this.authCheck(data)) return
          if (data && data.result_code === 1) {
            this.form.state = '2'

            this.alertText = "操作成功！"
            $('#my-alert').modal('toggle')
          } else {

            this.alertText = "操作异常！"
            $('#my-alert').modal('toggle')
          }

        }, (res) => { this.alertText = "操作异常"; $('#my-alert').modal('toggle') })
        },
        refund() {
          apis.refund(this.form._id).then(({data}) => {
          // if (this.authCheck(data)) return
          if (data && data.result_code === 1) {
            this.form.state = '12'

            this.alertText = "操作成功！"
            $('#my-alert').modal('toggle')
          } else {

            this.alertText = "操作异常！"
            $('#my-alert').modal('toggle')
          }

        }, (res) => { this.alertText = "操作异常"; $('#my-alert').modal('toggle') })
        },
        refunding() {
          document.getElementById("submit2").click()
          if (!this.valid2) return
            $(this.$refs.myModel).modal('close');
          apis.refunding(this.id, this.form2).then(({data}) => {
          // if (this.authCheck(data)) return
          if (data && data.result_code === 1) {
            this.form.state = '11'

            this.alertText = "操作成功！"
            $('#my-alert').modal('toggle')
          } else {

            this.alertText = "操作异常！"
            $('#my-alert').modal('toggle')
          }

        }, (res) => { this.alertText = "操作异常"; $('#my-alert').modal('toggle') })

        },
        generateQRcode(eid, id) {
          this.$nextTick(() => {
          // 拼接微信端项目详情页URL 待处理
          $("#fgy-project-qrcode").qrcode({
            width: 100,
            height: 100,
            text: `${process.env.WX_HOST.replace('{{eid}}', eid)}/wx/project/open/${id}`
          })
        })
        },
        audit(val) {
          if (val === 'pass' || val === 'restore') {
            if (this.form.etime <= new Date().getTime()) {
              this.alertText = "请设置正确的项目结束时间"
              $('#my-alert').modal('toggle')
              return
            }
          }
          if (val === 'pass') this.confirm = { show: true, header: '操作确认窗', content: '您确认开始筹款吗？', state: val }
            if (val === 'delete') this.confirm = { show: true, header: '操作确认窗', content: '您确认删除项目吗？', state: val }
              if (val === 'stop') this.confirm = { show: true, header: '操作确认窗口', content: '您确认暂停项目筹款吗？', state: val }
                if (val === 'restore') this.confirm = { show: true, header: '操作确认窗口', content: '您确认恢复项目的筹款吗？', state: val }
                  if (val === 'end') this.confirm = { show: true, header: '操作确认窗口', content: '您确认结束项目的筹款吗？注意：项目结束后将不能继续筹款！若是暂停项目 请使用暂停功能。', state: val }
                    if (val === 'refunding') this.confirm = { show: true, header: '操作确认窗口', content: '您确认要把项目状态改为退款中吗？', state: val }
                      if (val === 'refund') this.confirm = { show: true, header: '操作确认窗口', content: '您你确认项目的捐款都退款到捐款人那里了吗？若确认,项目将转为“已退款”状态,微信服务号推送“退款成功通知', state: val }
                    },
                  onConfirm(state) {
                    if (this.confirm.state === 'pass') this.passAudit()
                      if (this.confirm.state === 'delete') this.noPassAudit()
                        if (this.confirm.state === 'stop') this.stop()
                          if (this.confirm.state === 'restore') this.restore()
                            if (this.confirm.state === 'end') this.end()
                              if (this.confirm.state === 'refunding') this.refunding()
                                if (this.confirm.state === 'refund') this.refund()
                              },
                            onCancel() {
                              this.confirm.show = false
                            },
                            selectUserCheck(list) {
                              console.log('选了人', list.openid)
                              this.form.openid = list.openid
                              this.user = list
                            },
                            selectUserOpen() {
                              $('#user-popup').modal('toggle')
                            },
                            validate() {
                              if (this.form.type == '0' && this.form.etime != '') {
                                this.alertText = "长期筹款没有结束时间！"
                                $('#my-alert').modal('toggle')
                                this.valid = false
                                return
                              }

                              if (this.form.type == '1' && this.form.etime == '') {
                                this.alertText = "筹款必须填写结束日期！"
                                $('#my-alert').modal('toggle')
                                this.valid = false
                                return
                              }
                              if (this.form.recommenderType == '1' && this.form.recommenderDeadline == '') {

                                this.alertText = "官方推荐必须填写推荐期限！"
                                $('#my-alert').modal('toggle')
                                this.valid = false
                                return
                              }
                              if (this.form.recommenderType == '0' && this.form.recommenderDeadline != '') {

                                this.alertText = "无推荐不需要填写推荐期限！"
                                $('#my-alert').modal('toggle')
                                this.valid = false
                                return
                              }

                              if (this.form.type == '1' && this.form.etime <= this.form.stime) {
                                this.alertText = "结束时间必须大于发起时间"
                                $('#my-alert').modal('toggle')
                                this.valid = false
                                return
                              }

                              if (String(this.form.tmoney).includes('.')) {
                                this.alertText = "目标金额必须为整数！"
                                $('#my-alert').modal('toggle')
                                this.valid = false
                                return
                              }

                              if (String(this.form.invoiceMinMoney).includes('.')) {
                                this.alertText = "开据最低限额必须为整数！"
                                $('#my-alert').modal('toggle')
                                this.valid = false
                                return
                              }
                              console.log('this.form.openid', this.form.openid)
                              if (this.form.fundraisingType === '2' && !this.form.openid) {
                                this.alertText = "请选择求助人！"
                                $('#my-alert').modal('toggle')
                                this.valid = false
                                return
                              }
                            },
                            validate2() {
                              if (this.form.type == '1' && this.form.etime <= new Date().getTime()) {
                                this.alertText = "结束时间必须大于当前时间"
                                $('#my-alert').modal('toggle')
                                this.valid = false
                                return
                              }
                              if (this.form.recommenderType == '1' && this.form.recommenderDeadline <= new Date().getTime()) {

                                this.alertText = "推荐期限必须大于当前时间"
                                $('#my-alert').modal('toggle')
                                this.valid = false
                                return
                              }


                            }
                          }
                        }

                      </script>

                      <style>
                        .edui-container {
                          width: 100% !important;
                        }

                        .am-form .am-input-group {
                          margin-bottom: 10px;
                        }
                        .gps{
                          border: 1px solid #ccc;
                          background: #eee;
                          text-indent: 10px;
                        }
                      </style>